<template>
  <view class="u-page">
    <!-- 搜索表单组件 -->
    <opportunities-form
      @search="handleSearch"
      @reset="resetSearch"
    ></opportunities-form>

    <!-- 表格工具栏 -->
    <view class="table-toolbar">
      <up-button type="primary" @click="handleAdd">新增销售过程</up-button>
      <!-- <up-button
        type="error"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
        >批量删除</up-button
      >
      <up-button @click="handleExport">导出</up-button> -->
    </view>

    <!-- 列表区域 -->
    <up-list @scrolltolower="scrolltolower">
      <up-list-item
        v-for="(item, index) in tableData"
        :key="item.id"
        style="display: flex; justify-content: space-between"
      >
        <up-cell
          :title="item.customerName"
          :label="item.channelName"
          @click="handleEdit(item)"
        >
          <template #icon>
            <up-avatar
              shape="square"
              size="45"
              :text="item.employeeId.toString()"
              customStyle="margin: -3px 5px -3px 0"
            ></up-avatar>
          </template>
        </up-cell>
        <up-button type="primary" size="mini" @click="handleDelete(item)"
          >删除</up-button
        >
      </up-list-item>
      <template #footer>
        <view class="list-footer" v-if="loading">
          <up-loading-icon mode="circle" text="加载中..."></up-loading-icon>
        </view>
        <view class="list-footer" v-if="!hasMore">
          <text class="no-more-text">没有更多数据了</text>
        </view>
      </template>
    </up-list>

    <!-- 销售过程表单对话框 -->
    <up-modal
      :show="dialogVisible"
      :title="dialogType === 'add' ? '新增销售过程' : '编辑销售过程'"
      :showCancelButton="true"
      :showConfirmButton="true"
      @confirm="submitForm"
      @cancel="dialogVisible = false"
    >
      <view class="form-content">
        <up-form
          labelPosition="top"
          :model="salesOpportunitiesForm"
          :rules="salesOpportunitiesFormRules"
          ref="salesOpportunitiesFormRef"
        >
          <up-form-item label="客户ID" prop="customerId" :borderBottom="true">
            <up-input
              v-model="salesOpportunitiesForm.customerId"
              placeholder="请输入客户ID"
              border="none"
              type="number"
            ></up-input>
          </up-form-item>
          <up-form-item label="渠道ID" prop="channelId" :borderBottom="true">
            <up-input
              v-model="salesOpportunitiesForm.channelId"
              placeholder="请输入渠道ID"
              border="none"
              type="number"
            ></up-input>
          </up-form-item>
          <up-form-item label="员工ID" prop="employeeId" :borderBottom="true">
            <up-input
              v-model="salesOpportunitiesForm.employeeId"
              placeholder="请输入员工ID"
              border="none"
              type="number"
              :disabled="dialogType === 'add'"
            ></up-input>
          </up-form-item>
          <up-form-item
            label="预期金额"
            prop="expectedAmount"
            :borderBottom="true"
          >
            <up-input
              v-model="salesOpportunitiesForm.expectedAmount"
              placeholder="请输入预期金额"
              border="none"
              type="number"
            ></up-input>
          </up-form-item>
          <up-form-item
            label="当前阶段"
            prop="currentStage"
            :borderBottom="true"
            @click="showStageSelect = true"
          >
            <up-input
              v-model="stageDisplayText"
              placeholder="请选择阶段"
              border="none"
              disabled
              disabledColor="#ffffff"
            ></up-input>
            <template #right>
              <up-icon name="arrow-right"></up-icon>
            </template>
          </up-form-item>
        </up-form>
      </view>
    </up-modal>

    <!-- 阶段选择器 -->
    <up-action-sheet
      :show="showStageSelect"
      :actions="stageOptions"
      title="请选择阶段"
      @close="showStageSelect = false"
      @select="stageSelect"
    ></up-action-sheet>

    <!-- 批量操作确认弹窗 -->
    <up-modal
      :show="confirmVisible"
      title="确认操作"
      :content="confirmContent"
      :showCancelButton="true"
      @confirm="confirmAction"
      @cancel="confirmVisible = false"
    ></up-modal>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import {
  getOpportunitiesList,
  addOpportunity,
  updateOpportunity,
  deleteOpportunities,
} from "@/api/salesOpportunities";
import OpportunitiesForm from "@/components/OpportunitiesForm.vue";

// 选项数据
const channelTypeOptions = [
  { name: "线上", value: 1, type: "success" },
  { name: "线下", value: 2, type: "info" },
  { name: "合作伙伴", value: 3, type: "warning" },
  { name: "直销", value: 4, type: "primary" },
  { name: "代理商", value: 5, type: "danger" },
];

const stageOptions = [
  { name: "初步接触", value: 1, type: "info" },
  { name: "需求确认", value: 2, type: "warning" },
  { name: "方案制定", value: 3, type: "primary" },
  { name: "商务谈判", value: 4, type: "success" },
  { name: "合同签订", value: 5, type: "danger" },
];

// 搜索表单
const searchForm = reactive({
  customerName: "",
  channelName: "",
  channelType: "",
  currentStage: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);
const hasMore = ref(true);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref("add");
const showStageSelect = ref(false);
const confirmVisible = ref(false);
const confirmContent = ref("");
const confirmCallback = ref(null);

// 表单数据
const salesOpportunitiesForm = reactive({
  id: null,
  customerId: "",
  channelId: "",
  expectedAmount: "",
  currentStage: 1,
  employeeId: 1,
});

// 表单验证规则
const salesOpportunitiesFormRules = reactive({
  customerId: {
    type: "number",
    required: true,
    message: "请输入客户ID",
    trigger: ["blur"],
  },
  channelId: {
    type: "number",
    required: true,
    message: "请输入渠道ID",
    trigger: ["blur"],
  },
  employeeId: {
    type: "number",
    required: true,
    message: "请输入员工ID",
    trigger: ["blur"],
  },
  expectedAmount: {
    type: "number",
    required: true,
    message: "请输入预期金额",
    trigger: ["blur"],
  },
  currentStage: {
    type: "number",
    required: true,
    message: "请选择阶段",
    trigger: ["blur"],
  },
});

// 表单引用
const salesOpportunitiesFormRef = ref(null);

// 计算属性
const stageDisplayText = computed(() => {
  if (!salesOpportunitiesForm.currentStage) return "";
  return stageFilter(salesOpportunitiesForm.currentStage);
});

// 生命周期
onMounted(() => {
  fetchOpportunitiesList();
});

// 页面触底时加载更多
onReachBottom(async () => {
  if (hasMore.value) {
    const res = await getOpportunitiesList({
      ...searchForm,
      current: pagination.currentPage + 1,
      size: pagination.pageSize,
    });
    if (res.success) {
      tableData.value = [...tableData.value, ...res.data.list];
      pagination.currentPage++;
      pagination.total = res.data.total;
      hasMore.value = tableData.value.length < res.data.total;
    }
  }
});

// 上拉刷新时加载最新数据
onPullDownRefresh(async () => {
  const res = await getOpportunitiesList({
    ...searchForm,
    current: 1,
    size: pagination.pageSize,
  });
  if (res.success) {
    tableData.value = res.data.list;
    pagination.currentPage = 1;
  }
  pagination.total = res.data.total;
  hasMore.value = tableData.value.length < res.data.total;
});

// 方法
const fetchOpportunitiesList = async () => {
  loading.value = true;

  try {
    const response = await getOpportunitiesList({
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize,
    });

    if (response.success) {
      if (pagination.currentPage === 1) {
        tableData.value = response.data.list;
      } else {
        tableData.value = [...tableData.value, ...response.data.list];
      }

      pagination.total = response.data.total;
      hasMore.value = tableData.value.length < response.data.total;
    } else {
      uni.showToast({
        title: "获取数据失败",
        icon: "none",
      });
    }
  } catch (error) {
    uni.showToast({
      title: "网络错误",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

const scrolltolower = async () => {
  if (hasMore.value) {
    const res = await getOpportunitiesList({
      current: pagination.currentPage + 1,
      size: pagination.pageSize,
    });
    if (res.success) {
      tableData.value = [...tableData.value, ...res.data.list];
      pagination.currentPage++;
    }
  }
};

const channelTypeFilter = (value) => {
  const item = channelTypeOptions.find((item) => item.value === value);
  return item ? item.name : "";
};

const stageFilter = (value) => {
  const item = stageOptions.find((item) => item.value === parseInt(value));
  return item ? item.name : "";
};

const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return `¥${parseFloat(value).toFixed(2)}`;
};

const handleSearch = (form) => {
  Object.assign(searchForm, form);
  pagination.currentPage = 1;
  fetchOpportunitiesList();
};

const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchOpportunitiesList();
};

const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  salesOpportunitiesForm.employeeId = 1;
  salesOpportunitiesForm.currentStage = 1;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.keys(salesOpportunitiesForm).forEach((key) => {
    salesOpportunitiesForm[key] = row[key];
  });
  dialogVisible.value = true;
};

const stageSelect = (e) => {
  salesOpportunitiesForm.currentStage = e.value;
  showStageSelect.value = false;
  salesOpportunitiesFormRef.value.validateField("currentStage");
};

const handleDelete = (row) => {
  confirmContent.value = `确定要删除销售过程 "${row.customerName}" 吗？`;
  confirmVisible.value = true;
  confirmCallback.value = async () => {
    try {
      const response = await deleteOpportunities([row.id]);
      if (response.success) {
        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
        pagination.currentPage = 1;
        fetchOpportunitiesList();
      }
    } catch (error) {
      uni.showToast({
        title: "删除失败",
        icon: "none",
      });
    }
  };
};

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    uni.showToast({
      title: "请选择要删除的销售过程",
      icon: "none",
    });
    return;
  }

  confirmContent.value = `确定要删除选中的 ${selectedRows.value.length} 个销售过程吗？`;
  confirmVisible.value = true;
  confirmCallback.value = async () => {
    try {
      const response = await deleteOpportunities(
        selectedRows.value.map((row) => row.id)
      );
      if (response.success) {
        uni.showToast({
          title: "批量删除成功",
          icon: "success",
        });
        pagination.currentPage = 1;
        fetchOpportunitiesList();
      }
    } catch (error) {
      uni.showToast({
        title: "批量删除失败",
        icon: "none",
      });
    }
  };
};

const confirmAction = () => {
  confirmVisible.value = false;
  if (typeof confirmCallback.value === "function") {
    confirmCallback.value();
    confirmCallback.value = null;
  }
};

const handleExport = async () => {
  try {
    uni.showToast({
      title: "导出成功",
      icon: "success",
    });
  } catch (error) {
    uni.showToast({
      title: "导出失败",
      icon: "none",
    });
  }
};

const submitForm = async () => {
  if (!salesOpportunitiesFormRef.value) return;
  if (!(await salesOpportunitiesFormRef.value.validate())) return;
  try {
    let response;
    if (dialogType.value === "add") {
      response = await addOpportunity(salesOpportunitiesForm);
    } else {
      response = await updateOpportunity(salesOpportunitiesForm);
    }

    if (response.success) {
      uni.showToast({
        title: dialogType.value === "add" ? "新增成功" : "更新成功",
        icon: "success",
      });
      dialogVisible.value = false;
      pagination.currentPage = 1;
      fetchOpportunitiesList();
    }
  } catch (error) {
    uni.showToast({
      title: error.message,
      icon: "none",
    });
  }
};

const resetForm = () => {
  if (salesOpportunitiesFormRef.value) {
    salesOpportunitiesFormRef.value.resetFields();
  }

  Object.keys(salesOpportunitiesForm).forEach((key) => {
    if (key === "currentStage") {
      salesOpportunitiesForm[key] = 1;
    } else if (key === "employeeId") {
      salesOpportunitiesForm[key] = 1;
    } else {
      salesOpportunitiesForm[key] = "";
    }
  });
};
</script>

<style lang="scss" scoped>
.u-page {
  padding: 15px;
}

.table-toolbar {
  margin: 15px 0;
  display: flex;
  gap: 10px;
}

.list-footer {
  padding: 15px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-text,
.no-more-text {
  font-size: 14px;
  color: #909399;
  margin-left: 10px;
}

.cell-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount {
  font-size: 16px;
  font-weight: bold;
  color: #2979ff;
}

.stage-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  margin-top: 5px;
}

.stage-1 {
  background-color: #909399;
  color: #ffffff;
}

.stage-2 {
  background-color: #ff9900;
  color: #ffffff;
}

.stage-3 {
  background-color: #2979ff;
  color: #ffffff;
}

.stage-4 {
  background-color: #19be6b;
  color: #ffffff;
}

.stage-5 {
  background-color: #fa3534;
  color: #ffffff;
}

.form-content {
  padding: 10px;
}
</style>
